import json
from typing import Optional, Dict, Any

import lark_oapi as lark
from lark_oapi.api.calendar.v4 import *


def get_calendar_event_details(
    calendar_id: str,
    event_id: str,
    user_access_token: str,
    max_attendee_num: int = 10,
    enable_debug_log: bool = False
) -> Optional[Dict[str, Any]]:
    """
    获取日历事件详情
    
    Args:
        calendar_id: 日历ID
        event_id: 事件ID  
        user_access_token: 用户访问令牌
        max_attendee_num: 最大参与者数量，默认10
        enable_debug_log: 是否启用调试日志，默认False
        
    Returns:
        成功时返回事件详情字典，失败时返回None
    """
    # 创建client
    log_level = lark.LogLevel.DEBUG if enable_debug_log else lark.LogLevel.INFO
    client = lark.Client.builder() \
        .enable_set_token(True) \
        .log_level(log_level) \
        .build()

    # 构造请求对象
    request: GetCalendarEventRequest = GetCalendarEventRequest.builder() \
        .calendar_id(calendar_id) \
        .event_id(event_id) \
        .max_attendee_num(max_attendee_num) \
        .build()

    # 发起请求
    option = lark.RequestOption.builder().user_access_token(user_access_token).build()
    response: GetCalendarEventResponse = client.calendar.v4.calendar_event.get(request, option)

    # 处理失败返回
    if not response.success():
        error_message = f"获取日历事件失败: code={response.code}, msg={response.msg}, log_id={response.get_log_id()}"
        if enable_debug_log:
            error_message += f", resp=\n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}"
        lark.logger.error(error_message)
        return None

    # 处理业务结果
    event_data = response.data
    if enable_debug_log:
        lark.logger.info(f"成功获取事件详情: {lark.JSON.marshal(event_data, indent=4)}")
    
    return event_data


def main():
    """示例用法"""
    # 示例参数
    theCalendarIdentifier = "feishu.cn_eimFrJiP8ejNl9D7rPgJle@group.calendar.feishu.cn"
    theEventIdentifier = "7541f094-a960-409c-bb38-8bbf7e4ba2cc_0"
    theUserAccessToken = "u-cfKIDr80l7dFb7rQYIubFKhl5Rtkg1wXU2004140257y"
    
    event_details = get_calendar_event_details(
        calendar_id=theCalendarIdentifier,
        event_id=theEventIdentifier,
        user_access_token=theUserAccessToken,
        max_attendee_num=10,
        enable_debug_log=True
    )
    
    if event_details:
        print("成功获取事件详情")
        # 这里可以进一步处理事件数据
    else:
        print("获取事件详情失败")


if __name__ == "__main__":
    main()